package com.yonyou.wdt.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;

@Component
public class CommonService {
    @Value("${ys.config.tenantId}")
    public String tenantId;
    @Resource
    public YonsuiteService yonsuiteService;
    private static final int pageSize = 400;
    // 2024-05-10 调价单查询接口更换价格表查询
    // private static final int status = 1;
    private static final String status = "VALID";
    /**
     * @Description 价格表查询
     **/
    public JSONObject priceListQuery(String org, String timestamp, QueryDto dto) {
        JSONObject responseJson = new JSONObject();
        if (RedisUtils.get(dto.getTenantId() + ":price:" + org) == null) {
            // 根据调出组织，查询物料价格 - 调价单查询
            HashMap<String, Object> queryMap = new HashMap<>();
           // queryMap.put("priceTemplateId", priceTemplateId);  // 价格模板ID
            queryMap.put("status", status);  // 状态，待审批:0,已生效:1,已驳回:2,审批中:3
            HashMap<String, Object> simpleVOsMap = new HashMap<>();
            simpleVOsMap.put("op", "elt");
            simpleVOsMap.put("field", "beginDate");
            simpleVOsMap.put("value1", timestamp);
            HashMap<String, Object> simpleVOsMap1 = new HashMap<>();
            simpleVOsMap1.put("op", "egt");
            simpleVOsMap1.put("field", "endDate");
            simpleVOsMap1.put("value1", timestamp);
            HashMap<String, Object> simpleVOsMap2 = new HashMap<>();
            // simpleVOsMap2.put("op", "eq");
            // simpleVOsMap2.put("field", "creationOrgId.code");
            // simpleVOsMap2.put("value1", org);
            // 2024-05-10 调价单查询接口更换价格表查询
            simpleVOsMap2.put("op", "eq");
            simpleVOsMap2.put("field", "orgScope.code");
            simpleVOsMap2.put("value1", org);
            ArrayList<HashMap<String, Object>> simpleVOsList = new ArrayList<>();
            simpleVOsList.add(simpleVOsMap);
            simpleVOsList.add(simpleVOsMap1);
            simpleVOsList.add(simpleVOsMap2);
            queryMap.put("simpleVOs", simpleVOsList);
            queryMap.put("pageSize", pageSize);
            int pageIndex = 1;
            while (true) {
                try {
                    queryMap.put("pageIndex", pageIndex);
                    // 价格表查询
                    JSONObject priceListQueryResponse = yonsuiteService.priceListQuery(queryMap, dto);
                    if (priceListQueryResponse != null && "200".equals(priceListQueryResponse.getStr("code"))) {
                        JSONObject data = priceListQueryResponse.getJSONObject("data");
                        if (null != data.getJSONArray("recordList") && !data.getJSONArray("recordList").isEmpty()) {
                            if (responseJson.containsKey("data")) {
                                JSONArray oldData = responseJson.getJSONArray("data");
                                oldData.addAll(data.getJSONArray("recordList"));
                                responseJson.set("data", oldData);
                            } else {
                                responseJson.set("data", data.getJSONArray("recordList"));
                            }
                        }
                        // 是否为最后一页数据,跳出循环
                        if (data.getInt("recordCount") <= pageIndex * pageSize) {
                            break;
                        }
                        pageIndex++;
                    } else {
                        responseJson.set("code", "999");
                        if (priceListQueryResponse != null) {
                            responseJson.set("message", priceListQueryResponse.getStr("message"));
                        } else {
                            responseJson.set("message", "价格表查询接口返回信息为空,请重试");
                        }
                        return responseJson;
                    }
                } catch (Exception e) {
                    responseJson.set("code", "999");
                    responseJson.set("message", e.getMessage());
                    return responseJson;
                }
            }
            responseJson.set("code", "200");
            responseJson.set("message", "查询成功");
            if (null == responseJson.getJSONArray("data") || responseJson.getJSONArray("data").isEmpty()) {
                responseJson.set("data", new JSONArray());
            }
            // 调价单数据存入Redis
            boolean isSuccessBool = redisSavePrice(dto, responseJson, org);
            int errorIndex = 0;
            while (!isSuccessBool) {
                isSuccessBool = redisSavePrice(dto, responseJson, org);
                if (errorIndex == 5) {
                    break;
                }
                errorIndex++;
            }
        } else {
            responseJson = (JSONObject) RedisUtils.get(dto.getTenantId() + ":price:" + org);
        }
        return responseJson;
    }
    /**
     * @Description 价格表数据根据租户:price:时间:org
     **/
    private static boolean redisSavePrice(QueryDto dto, JSONObject responseJson, String org) {
        JSONArray priceNewList = new JSONArray();
        for (Object dataObj : responseJson.getJSONArray("data")) {
            JSONObject priceJson = (JSONObject) dataObj;
            JSONObject priceNewJson = new JSONObject();
            priceNewJson.set("productId_code", priceJson.getStr("productId_code"));
            priceNewJson.set("adjustGradients_price", priceJson.getBigDecimal("recordGradients_price"));
            priceNewList.add(priceNewJson);
        }
        if (!priceNewList.isEmpty()) {
            responseJson.set("data", priceNewList);
            return RedisUtils.set(dto.getTenantId() + ":price:" + org, responseJson, 82800);
        } else {
            return true;
        }
    }

}
